package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class
RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //查询请求
    @RequestMapping("/list")
    @RequiredPermission(name = "角色查看",expression = "role.list")
    public String list(QueryObject qo, Model model) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "/role/list";
    }
    //去增加或者去修改页面
    @RequestMapping("/input")
    @RequiredPermission(name = "角色修改或者增加",expression = "role.input")
    public String input(Long id, Model model) {
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        model.addAttribute("permission",permissionService.listAll());
        if (id != null) {
            Role role = roleService.get(id);
            model.addAttribute("role", role);
            //编辑时查询角色的权限集合
            model.addAttribute("rolePermissions", permissionService.selectByRoleId(id));
        }
        return "/role/input";
    }

    //新增或者修改
    @RequestMapping("/saveOrUpdate")
    public String update(Role role, Long[] ids) {
        if (role.getId() == null) {
            //如果id等于空那就新增
            roleService.save(role,ids);
        } else {
            //如果id不为空那就去修改
            roleService.update(role,ids);
        }
        //修改或者插入完以后使用重定向到查询页面
        return "redirect:/role/list";
    }
    //删除请求
    @RequestMapping("/delete")
    @RequiredPermission(name = "角色删除",expression = "role.delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        //删除以后重定向到查询页面
        return "redirect:/role/list";
    }
}
